package com.hanserwei.community.controller;

import com.hanserwei.community.entity.common.ApiResponse;
import com.hanserwei.community.entity.po.MeterCategory;
import com.hanserwei.community.entity.request.meter.MeterCategorySaveRequest;
import com.hanserwei.community.enums.ResponseCodeEnum;
import com.hanserwei.community.service.MeterCategoryService;
import com.hanserwei.community.service.MeterRecordService;
import com.hanserwei.community.uitils.ThrowUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/meter/category")
@Tag(name = "MeterCategoryController", description = "抄表类型管理接口")
@RequiredArgsConstructor
public class MeterCategoryController {

    private final MeterCategoryService meterCategoryService;
    private final MeterRecordService meterRecordService;

    @Operation(summary = "查询抄表类型列表")
    @GetMapping("/list")
    public ApiResponse<List<MeterCategory>> list() {
        List<MeterCategory> list = meterCategoryService.listAll();
        return ApiResponse.success("查询成功！", list);
    }

    @Operation(summary = "新增抄表类型")
    @PostMapping("/add")
    public ApiResponse<Boolean> add(@RequestBody MeterCategorySaveRequest request) {
        meterCategoryService.createCategory(request);
        return ApiResponse.success("新增成功！", true);
    }

    @Operation(summary = "更新抄表类型")
    @PostMapping("/update/{id}")
    public ApiResponse<Boolean> update(@PathVariable Integer id, @RequestBody MeterCategorySaveRequest request) {
        meterCategoryService.updateCategory(id, request);
        return ApiResponse.success("更新成功！", true);
    }

    @Operation(summary = "删除抄表类型")
    @DeleteMapping("/delete")
    public ApiResponse<Boolean> delete(@RequestParam("id") Integer id) {
        ThrowUtils.throwIf(id == null || id <= 0, ResponseCodeEnum.INVALID_PARAMETER, "类型ID参数错误！");
        Long usage = meterRecordService.lambdaQuery().eq(com.hanserwei.community.entity.po.MeterRecord::getTypeId, id).count();
        ThrowUtils.throwIf(usage != null && usage > 0, ResponseCodeEnum.INVALID_PARAMETER, "存在关联抄表记录，无法删除！");
        boolean result = meterCategoryService.removeById(id);
        ThrowUtils.throwIf(!result, ResponseCodeEnum.SYSTEM_ERROR, "删除失败！");
        return ApiResponse.success("删除成功！", true);
    }
}
